package com.bxl.island;

import java.util.*;

/**
 * 计算孤岛数量
 *
 * @author baixl
 * @date 2021/4/2
 */
public class Island {
    public static void main(String[] args) {
       // int[][] a = {{1, 1, 1, 1, 0}, {1, 1, 0, 1, 0}, {1, 1, 0, 0, 0}, {0, 0, 0, 0, 0}};
        int[][] a = {{1, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}};
        System.out.println(getIslandNum(a));
    }

    public static int getIslandNum(int[][] arys) {
        List<Map<String, String>> islands = new ArrayList<>();

        int m = arys.length;
        int n = arys[0].length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {

                if (arys[i][j] == 1) {
                    Map<String, String> curMap = null;

                    String key = i + "_" + j;
                    for (Map<String, String> island : islands) {
                        if (island.keySet().contains(key)) {
                            curMap = island;
                            break;
                        }
                    }
                    if (Objects.isNull(curMap)) {
                        curMap = new HashMap<>();
                        curMap.put(key, "1");
                        islands.add(curMap);
                    }
                    /*if (i > 0 && arys[i - 1][j] == 1) {
                        curMap.put((i - 1) + "_" + j, "1");
                    }

                    if (j > 0 && arys[i][j - 1] == 1) {
                        curMap.put(i + "_" + (j - 1), "1");
                    }*/

                    if (i < (m - 1) && arys[i + 1][j] == 1) {
                        curMap.put((i + 1) + "_" + j, "1");
                    }

                    if (j < (n - 1) && arys[i][j + 1] == 1) {
                        curMap.put(i + "_" + (j + 1), "1");
                    }
                }


            }
        }
        return islands.size();

    }
}
